package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
	"sync"
	"time"
)

func GetFoo(url string, wg *sync.WaitGroup) error {
	defer wg.Done()
	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	fmt.Println(string(body))
	return nil
}

func PostFoo(url string, wg *sync.WaitGroup, flag *int) error {
	defer wg.Done()
	jsonByte := bytes.NewBuffer([]byte(`{"name": "hhhhabs"}`))
	resp, err := http.Post(url, "application/json", jsonByte)
	if err != nil {
		*flag += 1
		fmt.Println("err is ", err.Error())
		return err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		*flag += 1
		fmt.Println("err is ", err.Error())
		return err
	}
	if len(string(body)) > 27 {
		*flag += 1
	}
	// fmt.Println(string(body))
	return nil
}

func main() {
	startTime := time.Now().Unix()
	var wg sync.WaitGroup
	var flag int
	for i := 0; i < 10000; i++ {
		wg.Add(1)
		urlStr := "http://127.0.0.1:8091/v1/example/echo"
		go PostFoo(urlStr, &wg, &flag)
	}
	wg.Wait()
	fmt.Printf("请求失败： %v", flag)
	fmt.Printf("请求结束：%v", time.Now().Unix()-startTime)
}
